package com.item.read.action;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.item.read.util.HttpUtils;
import org.jetbrains.annotations.NotNull;

import java.io.*;
import java.util.jar.JarEntry;
import java.util.jar.JarOutputStream;

public class PullSourceAction extends AnAction {
    private static final String sourceUrl = "https://gitee.com/dulinzhi/simple-read/raw/master/src/main/resources/bookSource.json";
    @Override
    public void actionPerformed(@NotNull AnActionEvent e) {
        String data = HttpUtils.get(sourceUrl);
        String path = this.getClass().getResource("/bookSource.json").getPath();
        try {
            signWithJarSignerAPI(data,
                    java.net.URLDecoder.decode(
                            path.substring(0,path.lastIndexOf("/")-1)
                                    .replace("file:/","")
                                    .replace("file://",""),"UTF-8"));
        } catch (Throwable ex) {
            ex.printStackTrace();
        }
    }
    private static void signWithJarSignerAPI(String data,String jarName)
            throws Throwable {
        JarOutputStream fileOutputStream = new JarOutputStream(new FileOutputStream(jarName));
        JarEntry entry=new JarEntry("bookSource.json");
        fileOutputStream.putNextEntry(entry);
        fileOutputStream.write(data.getBytes("utf-8"));
        fileOutputStream.close();
    }
}
